package com.czhoujunlv.weather;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class cityWeatherFragment extends Fragment {

    TextView temp,text,feel_like,rh,wind_class,wind_dir,uptime,location;
    RecyclerView future;
    WeatherBean weatherBean;
    List<WeatherBean.ResultEntity.ForecastsEntity> future_item = new ArrayList<>();
    String url1 = "http://api.map.baidu.com/weather/v1/?district_id=";
    String url2 = "&data_type=all&ak=NUN023B0jtoCDXGZiWxsxNmTPSTiRqrq&mcode=0A:35:AD:B7:E9:A2:46:C3:D7:AF:05:F1:1F:E2:12:9D:01:8E:9E:8A;com.c201801020243.zhoujunlv";
    String city;
    String res;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_city_weather, container, false);
        initView(view);
        Bundle bundle = getArguments();
        city = bundle.getString("city");
        String url = url1 + city + url2;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().get().url(url).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("请求失败",e.toString());
            }
            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                res = response.body().string();
                int log = DBmanage.updateCity(city, res);//检查有无新数据出现
                Gson gson = new Gson();
                weatherBean = gson.fromJson(res, WeatherBean.class);
                future_item = weatherBean.getResult().getForecasts();
                if (log <= 0) {//更新失败，没有这条城市记录，所以要增加这条记录进入数据库
                    DBmanage.addCity(city, future_item.get(0).getLow(), future_item.get(0).getHigh(), weatherBean.getResult().getNow().getTemp());
                    Log.i("插入成功：", "success");
                }
                if (!isDestroy(getActivity()) && isAdded()) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                future.setAdapter(new MyAdapter());
                                future.setLayoutManager(new LinearLayoutManager(getActivity()));
                                temp.setText(String.valueOf(weatherBean.getResult().getNow().getTemp()) + "℃");
                                rh.setText(String.valueOf(weatherBean.getResult().getNow().getRh()) + "%");
                                feel_like.setText(String.valueOf(weatherBean.getResult().getNow().getFeels_like()) + "℃");
                                text.setText(weatherBean.getResult().getNow().getText());
                                Date date = null;
                                try {
                                    date = new SimpleDateFormat("yyyyMMddHHmmSS").parse(weatherBean.getResult().getNow().getUptime());
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                String now = new SimpleDateFormat("yyyy/MM/dd").format(date);
                                uptime.setText(now);
                                wind_class.setText(weatherBean.getResult().getNow().getWind_class());
                                wind_dir.setText(weatherBean.getResult().getNow().getWind_dir());
                                location.setText(weatherBean.getResult().getLocation().getCity() + " " + weatherBean.getResult().getLocation().getName());
                            } catch (Exception e) {
                                Log.i("切换异常：", e.toString());
                            }
                        }
                    });
                }
            }
        });
        return view;
    }
    protected boolean isDestroy(Activity activity) {
        return activity == null || activity.isFinishing() ||
                (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed());
    }
    public class MyAdapter extends RecyclerView.Adapter<MyHolder>{
        @NonNull
        @Override
        public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.item,parent,false);
            MyHolder myHolder = new MyHolder(view);
            return myHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyHolder holder, int position) {
                holder.data.setText(future_item.get(position).getWeek()+ " · ");
                holder.weather.setText(future_item.get(position).getText_day()+ " 转 " +future_item.get(position).getText_night());
                holder.temp_high.setText(String.valueOf(future_item.get(position).getHigh())+"℃");
                holder.temp_low.setText(String.valueOf(future_item.get(position).getLow())+"℃");
                Log.i("日期:",future_item.get(position).getWeek());
        }

        @Override
        public int getItemCount() {
            return future_item.size();
        }
    }
    public class MyHolder extends RecyclerView.ViewHolder {
        TextView data;
        TextView weather;
        TextView temp_high;
        TextView temp_low;
        public MyHolder(@NonNull View itemView) {
            super(itemView);
            data = itemView.findViewById(R.id.data);
            weather = itemView.findViewById(R.id.weather);
            temp_high = itemView.findViewById(R.id.temp_high);
            temp_low = itemView.findViewById(R.id.temp_low);

        }
    }














    private void initView(View view){
        temp = view.findViewById(R.id.temp);
        text = view.findViewById(R.id.text);
        feel_like = view.findViewById(R.id.feel_like);
        rh = view.findViewById(R.id.rh);
        wind_class = view.findViewById(R.id.wind_class);
        wind_dir = view.findViewById(R.id.wind_dir);
        uptime = view.findViewById(R.id.uptime);
        future = view.findViewById(R.id.future);
        location = view.findViewById(R.id.location);
    }
}